package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.DishDisableFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 菜品分页查询接口
     */
    @Override
    public PageResult getDishByPage(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> p = dishMapper.getDishByPage(dishPageQueryDTO);
        PageResult pr = new PageResult();
        pr.setRecords(p.getResult());
        pr.setTotal(p.getTotal());
        return pr;
    }

    /**
     * 新增菜品接口
     */
    @Transactional
    @Override
    public void addDish(DishDTO dishDTO) {
        //清空缓存
        Set keys = redisTemplate.keys("dish_categoryId_*");
        redisTemplate.delete(keys);
        /**
         * 需要增加同时增加dis和dish——flavor表
         */
        Dish dish = new Dish();
        List<DishFlavor> flavors = dishDTO.getFlavors();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.addDish(dish);
        if (ObjectUtils.isEmpty(flavors)){    //判断是否有口味，没有就返回
            return;
        }
        flavors.forEach(f -> f.setDishId(dish.getId()));
        dishMapper.addDishFlavor(flavors);
    }

    /**
     * 删除菜品接口
     */
    @Transactional
    @Override
    public void deleteBatchDish(List<Long> ids) {

        /**
         * 需要先判断菜品是否在售或者菜品是否在套餐里，如存在则抛异常无法删除
         */
        Integer count = dishMapper.countByStatus(ids);
        if (count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        }
        count = setmealMapper.countByDishId(ids);
        if (count > 0){
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //清空缓存
        Set keys = redisTemplate.keys("dish_categoryId_*");
        redisTemplate.delete(keys);
        dishMapper.deleteBatchDish(ids);
        dishMapper.deleteBatchDishFlavor(ids);
    }

    /**
     *根据id查询菜品接口
     */
    @Override
    public DishVO selectById(Long id) {
        DishVO dishVO = dishMapper.selectById(id);
        /*List<DishFlavor> dishFlavors = dishMapper.selectFlavorById(id);
        dishVO.setFlavors(dishFlavors);*/
        return dishVO;
    }

    /**
     * 修改菜品接口
     */
    @Transactional   //多条sql事务管理
    @Override
    public void updateDish(DishDTO dishDTO) {
        //清空缓存
        Set keys = redisTemplate.keys("dish_categoryId_*");
        redisTemplate.delete(keys);
        /**
         * 一般在真正项目开发中，一对多查修改，先修改主表，删除从表数据，再新增从表数据
         */
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateDish(dish);
        List<DishFlavor> flavors = dishDTO.getFlavors();
        List<Long> ids = new ArrayList<>();
        ids.add(dish.getId());
        dishMapper.deleteBatchDish(ids);
        if (ObjectUtils.isEmpty(flavors)){    //判断是否有口味
            return;
        }
        flavors.forEach(f -> f.setDishId(dish.getId()));
        dishMapper.addDishFlavor(dishDTO.getFlavors());

    }

    /**
     * 启售停售接口 直接合并到修改里
     */
    @Override
    public void startOrStopDish(Integer status, Long id) {
        if (status == 0){
            //如果菜品所在套餐为启售状态，那么菜品不能停售
            Integer count = dishMapper.countEnableSetmealsIncludeDish(id);
            if (count > 0){
                throw new DishDisableFailedException(MessageConstant.DISH_BE_RELATED_BY_ENABLE_SETMEAL);
            }
        }
        //清空缓存
        Set keys = redisTemplate.keys("dish_categoryId_*");
        redisTemplate.delete(keys);
        Dish dish = Dish.builder().id(id).status(status).build();
        dishMapper.updateDish(dish);
    }

    /**
     * 根据分类id查询菜品,包含口味
     */
    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        //如果缓存存在，直接返回缓存中的，不然去查询数据库，并将查询结果添加到redis中
        String dishKey = "dish_categoryId_" +  dish.getCategoryId();
        List<DishVO> list = (List<DishVO>) redisTemplate.opsForValue().get(dishKey);
        if (ObjectUtils.isNotEmpty(list)){
            return list;
        }
        list = dishMapper.listWithFlavor(dish);
        redisTemplate.opsForValue().set(dishKey, list);
        return list;
    }
}
